﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Linq;
using System.Threading;
using System.Xml;

namespace SmartSiteManagementSystem.Utils
{
    /// <summary>
    /// 字符串工具
    /// </summary>
    public class StringUtils
    {
        //将HTML去除
        public static string getDelHTML(string Htmlstring)
        {
            #region
            //删除脚本
            if (string.IsNullOrEmpty(Htmlstring))
            {
                return "";
            }

            Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            //删除HTML

            Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"-->", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"<!--.*", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            //Htmlstring =System.Text.RegularExpressions. Regex.Replace(Htmlstring,@"<A>.*</A>","");

            //Htmlstring =System.Text.RegularExpressions. Regex.Replace(Htmlstring,@"<[a-zA-Z]*=\.[a-zA-Z]*\?[a-zA-Z]+=\d&\w=%[a-zA-Z]*|[A-Z0-9]","");
            Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(amp|#38);", "&", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(lt|#60);", "<", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(gt|#62);", ">", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            Htmlstring = System.Text.RegularExpressions.Regex.Replace(Htmlstring, @"&#(\d+);", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            Htmlstring.Replace("<", "");

            Htmlstring.Replace(">", "");

            Htmlstring.Replace("\r\n", "");

            Htmlstring.Replace(" ", "");

            //Htmlstring=HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
            #endregion

            return Htmlstring;
        }

        /// <summary>
        /// 通过标签名过滤html
        /// </summary>
        /// <param name="htmlString">输入内容</param>
        /// <param name="tagNames">表签名，根据,分割</param>
        /// <returns></returns>
        public static string FilterHtmlByTagName(string htmlString, string tagNames)
        {
            if (!string.IsNullOrEmpty(htmlString))
            {
                //去除非a标签外的所有内容，a标签要保留自己的
                string[] arrTag = tagNames.Split(',');
                foreach (string tag in arrTag)
                {
                    if (tag == "a")
                    {
                        continue;
                    }
                    if (htmlString.Contains(tag))
                    {
                        htmlString = Regex.Replace(htmlString, @"(?is)<" + tag + "[^>]*?>.*?</" + tag + ">", "");
                    }
                }

                //去除onclick事件等事件
                //htmlString = Regex.Replace(htmlString, @"(?is)on[^=]*?=(['""])[^\1]*?\1", "");
                string pattern = @"(?<ScriptAttr>on\w+=\s*(['""\s]?)([/s/S]*[^\1]*?)\1)[\s|>|/>]";
                Regex r = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                foreach (Match m in r.Matches(htmlString))
                {
                    string attrs = m.Groups["ScriptAttr"].Value;
                    if (!string.IsNullOrEmpty(attrs))
                    {
                        htmlString = htmlString.Replace(attrs, string.Empty);
                    }
                }

                //去除a链接中不包含.m6go.的
                htmlString = Regex.Replace(htmlString, @"(?is)<a[^>]*?href=(['""])([^\1]*?)\1[^>]*?>(.*?)</a>", p => { if (p.Groups[2].Value.ToLower().Contains(".m6go.")) { return p.Groups[3].Value; } return p.Groups[2].Value; });
                htmlString = Regex.Replace(htmlString, @"http://file.m6go.com/([0-9a-zA-Z~_]{22})/?([0-9]*?)(?=['""])", "$0.jpeg");
            }
            return htmlString;
        }
        /// <summary>
        /// 通过标签名过滤html，适用于商家后台商品详情编辑
        /// </summary>
        /// <param name="htmlString">输入内容</param>
        /// <param name="tagNames">表签名，根据,分割</param>
        /// <Author> by renkaili 2015-05-26</Author>
        public static string FilterHtmlByTagName_Merchant(string htmlString, string tagNames)
        {
            if (!string.IsNullOrEmpty(htmlString))
            {
                //去除非a标签外的所有内容，a标签要保留自己的
                string[] arrTag = tagNames.Split(',');
                foreach (string tag in arrTag)
                {
                    if (tag == "a")
                    {
                        continue;
                    }
                    if (htmlString.Contains(tag))
                    {
                        htmlString = Regex.Replace(htmlString, @"(?is)<" + tag + "[^>]*?>.*?</" + tag + ">", "");
                    }
                }

                //去除onclick事件等事件
                //htmlString = Regex.Replace(htmlString, @"(?is)on[^=]*?=(['""])[^\1]*?\1", "");
                string pattern = @"(?<ScriptAttr>on\w+=\s*(['""\s]?)([/s/S]*[^\1]*?)\1)[\s|>|/>]";
                Regex r = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                foreach (Match m in r.Matches(htmlString))
                {
                    string attrs = m.Groups["ScriptAttr"].Value;
                    if (!string.IsNullOrEmpty(attrs))
                    {
                        htmlString = htmlString.Replace(attrs, string.Empty);
                    }
                }

                //去除a链接中不包含.m6go.的
                htmlString = Regex.Replace(htmlString, @"(?is)<a[^>]*?href=(['""])([^\1]*?)\1[^>]*?>(.*?)</a>", p => { if (!p.Groups[2].Value.ToLower().Contains(".m6go.") && !p.Groups[2].Value.ToLower().Contains(".gou.")) { return p.Groups[3].Value; } return p.Groups[0].Value; });
                htmlString = Regex.Replace(htmlString, @"http://file?([0-9]*?).m6go.com/([0-9a-zA-Z~_]{22})/?([0-9]*?)(?=['""])", "$0.jpeg");
            }
            return htmlString;
        }
        /// <summary>
        /// 是否是外网的的图片，适用于商家后台商品详情编辑
        /// </summary>
        /// <param name="text">传入的字符串</param>
        /// <returns> by renkaili 2015-05-27</returns>
        public static bool IsOuterImgUrl_Merchant(string text)
        {
            bool result = true;
            string pat = @"<img\s+[^>]*\s*src\s*=\s*([']?)(?<url>\S+)'?[^>]*>";
            Regex reg = new Regex(pat, RegexOptions.IgnoreCase);
            Match match = reg.Match(text.ToLower());
            while (match.Success)
            {
                Group group = match.Groups[2];
                result = group.Value.ToLower().Contains(".m6go.") || group.Value.ToLower().Contains(".gou.") ? true : false;
                if (!result) break;
                match = match.NextMatch();
            }
            return result;
        }
        /// <summary>
        /// 默认过滤 script,object,iframe,a
        /// </summary>
        /// <param name="htmlString">输入内容</param>
        /// <returns></returns>
        public static string FilterHtmlByTagName(string htmlString)
        {
            return FilterHtmlByTagName(htmlString, "script,object,iframe,a");
        }

        /// <summary>
        /// 清楚url中的危险字符
        /// </summary>
        /// <returns></returns>
        public static string ClearPerilousCharacterForUrl(string str)
        {
            if (string.IsNullOrEmpty(str))
                return str;
            else
                return str.Replace("<", "").Replace(">", "").Replace("'", "").Replace("\"", "");
        }

        /// <summary>
        /// 清楚json格式中的特殊字符
        /// </summary>
        /// <returns></returns>
        public static string ClearPerilousCharacterForJson(string str)
        {
            if (string.IsNullOrEmpty(str))
                return str;
            else
                return str.Replace("<", "").Replace(">", "").Replace("'", "").Replace("\"", "").Replace(",", "").Replace("#", "");
        }

        #region 将半角转换为全角
        //public static String ToSBC(String input)
        //{
        //    // 半角转全角：
        //    char[] c = input.ToCharArray();
        //    for (int i = 0; i < c.Length; i++)
        //    {
        //        if (c[i] == 32)
        //        {
        //            c[i] = (char)12288;
        //            continue;
        //        }
        //        if (c[i] < 127)
        //            c[i] = (char)(c[i] + 65248);
        //    }
        //    return new String(c);
        //}
        /// <summary>
        /// 将特殊字符半角转换为全角
        /// </summary>
        /// <param name="strInput"></param>
        /// <returns></returns>
        public static string ToSBC(string strInput)
        {
            char[] c = strInput.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (checkString(c[i].ToString()))
                {
                    if (c[i] == 32)
                    {
                        c[i] = (char)12288;
                        continue;
                    }
                    if (c[i] < 127)
                        c[i] = (char)(c[i] + 65248);
                }
            }
            return new string(c);

        }



        /// 严整特殊字符
        /// </summary>
        public static bool checkString(string source)
        {
            Regex regExp = new Regex("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）&;—|{}【】‘；：”“'。，、？]");

            // Regex regExp=new Regex("[~!@#$%^&*()=+[//]{}''/;:/?.,><`|！·￥…—（）//-、；：。，》《]");
            return regExp.IsMatch(source);
        }





        #endregion

        /// <summary>
        /// 检查同一个字符串中不相同字符的个数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int CheckStringChar(string Str)
        {
            string newStr = "";
            char oldChar = '_';
            for (int i = 0; i < Str.Length; i++)
            {
                if (oldChar != Str[i])
                {
                    oldChar = Str[i];
                    newStr += Str[i];
                }
            }

            return newStr.Length;
        }

        //public static long GetUnixTime()
        //{
        //    DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));

        //    DateTime nowTime = DateTime.Now;

        //    long unixTime = (long)Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero);
        //    return unixTime;
        //}

        /// <summary> 
        /// MD5加密字符串 
        /// </summary> 
        /// <param name="source">源字符串</param> 
        /// <returns>加密后的字符串</returns> 
        public static string Md5Fun(string source)
        {
            string back = "";
            using (var md5 = MD5.Create())
            {
                var result = md5.ComputeHash(Encoding.UTF8.GetBytes(source));
                var strResult = BitConverter.ToString(result);
                back= strResult.Replace("-", "").ToUpper();
            }
            return back;
        }

        public static string GetMD5(string str)
        {
            byte[] b = System.Text.Encoding.Default.GetBytes(str);
            b = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(b);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < b.Length; i++)
            {
                sb.Append(b[i].ToString("x").PadLeft(2, '0'));
            }

            return sb.ToString();
        }

        public static string Hex_MD5(string s)
        {
            //创建MD5对像
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            //将字符串转换成数组
            byte[] ba = Encoding.Default.GetBytes(s);
            //将数组加密 成  加密数组
            byte[] md55 = md5.ComputeHash(ba);
            //将加密数组编译成字符串
            // return Encoding.Default.GetString(md55);
            //
            string STR = "";
            //便利数组中元素转化成字符并拼接
            for (int I = 0; I < md55.Length; I++)
            {
                //X 表是10进制,X2表示16进制

                STR += md55[I].ToString("x2");

            }
            return STR;
         
        }
        /// <summary>
        /// 返回MD5（32）位，其中的字母为小写
        /// </summary>
        /// <param name="s"></param>
        /// <param name="_input_charset"></param>
        /// <returns></returns>
        public static string GetMD5_32(string s, string _input_charset)
        {
            MD5 md5 = new MD5CryptoServiceProvider();

            byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));

            StringBuilder sb = new StringBuilder(32);

            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }

            return sb.ToString();
        }

        //16位加密 
        public static string GetMd5_16(string ConvertString)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);

            t2 = t2.Replace("-", "");

            return t2;
        }

        /// <summary>
        /// 计算字符串长度，中文按照2个字节算
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int Len(string str)
        {
            if (string.IsNullOrEmpty(str))
                return 0;

            Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
            char[] stringChar = str.Trim().ToCharArray();
            StringBuilder sb = new StringBuilder();
            int nLength = 0;
            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()) || (stringChar[i] > 255))
                {
                    nLength += 2;
                }
                else
                {
                    nLength = nLength + 1;
                }

            }

            return nLength;
        }

        /// <summary>
        /// 截取中英文长度，中文、全角算2
        /// </summary>
        /// <returns></returns> 
        public static string CutString(string stringToSub, int length)
        {
            if (string.IsNullOrEmpty(stringToSub))
                return stringToSub;

            Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
            char[] stringChar = stringToSub.Trim().ToCharArray();
            StringBuilder sb = new StringBuilder();
            int nLength = 0;
            bool isCut = false;
            for (int i = 0; i < stringChar.Length; i++)
            {
                if (nLength >= length)
                {
                    isCut = true;
                    break;
                }
                if (regex.IsMatch((stringChar[i]).ToString()) || (stringChar[i] > 255))
                {
                    sb.Append(stringChar[i]);
                    nLength += 2;
                }
                else
                {
                    sb.Append(stringChar[i]);
                    nLength = nLength + 1;
                }

            }
            if (isCut)
                return sb.ToString() + "...";
            else
                return sb.ToString();

        }

        private const string amp = "&";
        private const string encodedAmp = "&amp;";

        /// <summary>
        /// 截取中英文长度，中文、全角算2
        /// </summary>
        /// <param name="stringToSub"></param>
        /// <param name="length"></param>
        /// <param name="suffixStr">截取字符串后的后缀字符串</param>
        /// <returns></returns>
        public static string CutString(string stringToSub, int length, string suffixStr)
        {
            if (string.IsNullOrEmpty(stringToSub))
                return stringToSub;

            Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
            char[] stringChar = stringToSub.Trim().ToCharArray();
            StringBuilder sb = new StringBuilder();
            int nLength = 0;
            bool isCut = false;
            for (int i = 0; i < stringChar.Length; i++)
            {
                if (nLength >= length)
                {
                    isCut = true;
                    break;
                }
                if (regex.IsMatch((stringChar[i]).ToString()) || (stringChar[i] > 255))
                {
                    sb.Append(stringChar[i]);
                    nLength += 2;
                }
                else
                {
                    sb.Append(stringChar[i]);
                    nLength = nLength + 1;
                }

            }
            if (isCut)
                return sb.ToString() + suffixStr;
            else
                return sb.ToString();

        }

        /// <summary>
        /// 随机中文码
        /// </summary>
        /// <returns></returns>
        public static string GetRndCh()
        {
            System.Text.Encoding gb = System.Text.Encoding.Default;//获取GB2312编码页（表）
            object[] bytes = CreateRegionCode(4);//调用函数产生4个随机中文汉字编码
            string[] str = new string[4];
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            for (int i = 0; i < 4; i++)
            {
                //根据汉字编码的字节数组解码出中文汉字
                str[i] = gb.GetString((byte[])Convert.ChangeType(bytes[i], typeof(byte[])));
                sb.Append(str[i].ToString());
            }
            return sb.ToString();
        }

        /// <summary>
        /// 随机中文
        /// </summary>
        /// <returns></returns>
        public static string GetRndCh2()
        {
            string _availableLetters = @"的一是在了不和有大这主中人上为们地个用工时要动国产以我到他会作来分生对于学下级就年阶义发成部民可出能方进同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批如应形想制心样干都向变关点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培著河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫康遵牧遭幅园腔订香肉弟屋敏恢忘衣孙龄岭骗休借丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩";
            List<char> code = new List<char>();
            Random rnd = new Random();
            string rndstr = string.Empty;
            for (int i = 0; i < 4; i++)
            {
                int seed = rnd.Next(0, _availableLetters.Length - 1);
                char temp = _availableLetters[seed];
                rndstr += temp;
            }

            return rndstr;

        }

        /// <summary>
        /// 产生随机中文汉字编码
        /// </summary>
        /// <param name="strlength"></param>
        /// <returns></returns>
        public static object[] CreateRegionCode(int strlength)
        {
            //定义一个字符串数组储存汉字编码的组成元素
            string[] rBase = new String[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
            Random rnd = new Random();
            object[] bytes = new object[strlength];

            for (int i = 0; i < strlength; i++)
            {
                //区位码第1位
                int r1 = rnd.Next(11, 14);
                string str_r1 = rBase[r1].Trim();

                //区位码第2位
                rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);
                int r2;
                if (r1 == 13)
                {
                    r2 = rnd.Next(0, 7);
                }
                else
                {
                    r2 = rnd.Next(0, 16);
                }
                string str_r2 = rBase[r2].Trim();

                //区位码第3位
                rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i);//更换随机种子
                int r3 = rnd.Next(10, 16);
                string str_r3 = rBase[r3].Trim();

                //区位码第4位
                rnd = new Random(r3 * unchecked((int)DateTime.Now.Ticks) + i);
                int r4;
                if (r3 == 10)
                {
                    r4 = rnd.Next(1, 16);
                }
                else if (r3 == 15)
                {
                    r4 = rnd.Next(0, 15);
                }
                else
                {
                    r4 = rnd.Next(0, 16);
                }
                string str_r4 = rBase[r4].Trim();

                //定义两个字节变量存储产生的随机汉字区位码
                byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
                byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);

                //将两个字节变量存储在字节数组中
                byte[] str_r = new byte[] { byte1, byte2 };

                //将产生的一个汉字的字节数组放入object数组中
                bytes.SetValue(str_r, i);
            }
            return bytes;
        }

        /// <summary>
        /// Base64加密方法
        /// </summary>
        /// <param name="str">输入字符串</param>
        static public string getBase64Encoding(string str)
        {
            return System.Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(str));
        }

        /// <summary>
        /// Base64解密方法
        /// </summary>
        /// <param name="pwdString">加密字符串</param>

        static public string getBase64Decoding(string pwdString)
        {
            try
            {
                return System.Text.Encoding.Default.GetString(System.Convert.FromBase64String(pwdString));
            }
            catch (Exception exp)
            {
                return exp.Message;
            }
        }

        /// <summary>
        /// 检查两个字符串是否相同，默认忽略大小写
        /// </summary>
        /// <param name="s1"></param>
        /// <param name="s2"></param>
        /// <param name="isIgnoreCase"></param>
        /// <returns></returns>
        public static bool IsSame(string s1, string s2, bool isIgnoreCase = true)
        {
            return s1.Equals(s2, isIgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
        }


        //默认密钥
        private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        private static string _GetEncryptKey()
        {
            string Code = "SSMS_2015";
            return Md5Fun(Code).Substring(0, 8);

        }
        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>       
        /// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
        public static string EncryptDES(string encryptString)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(_GetEncryptKey().Substring(0, 8));
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }

        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>       
        /// <returns>解密成功返回解密后的字符串，失败返源串</returns>
        public static string DecryptDES(string decryptString)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(_GetEncryptKey());
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }

        /// <summary>
        /// 判断给定字符串是否在数组里
        /// </summary>
        /// <param name="ss"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool isExist(string[] ss, string str)
        {
            List<string> ls = new List<string>(ss);
            foreach (string s in ls)
            {
                if (str.Equals(s))
                    return true;
            }
            return false;
        }


        #region 生成随机数
        #region 生成随机数（字母数字混合）
        /// <summary>
        /// 生成随机数（字母数字混合）
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string RndStr(int length)
        {
            string str = "1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z";

            string[] strArr = str.Split(',');
            string code = string.Empty;

            Random random = new Random(GetRandomSeed);

            for (int i = 0; i < length; i++)
            {
                code += strArr[random.Next(0, strArr.Length)];
            }
            return code;
        }
        #endregion

        #region 生成随机数（纯数字）
        /// <summary>
        /// 生成随机数（纯数字）
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string RndStrDigital(int length)
        {
            string str = "1,2,3,4,5,6,7,8,9,0";

            string[] strArr = str.Split(',');
            string code = string.Empty;

            Random random = new Random(DateTime.Now.Millisecond);

            for (int i = 0; i < length; i++)
            {
                code += strArr[random.Next(0, strArr.Length)];
            }
            return code;
        }

        /// <summary>
        /// 利用源数据生成验证码，清楚规则可以猜出使用
        /// </summary>
        /// <param name="srcData"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string RndStrDigital(string srcData,int length)
        {
            string str = srcData;
            string[] strArr = new string[srcData.Length];
            int str_idx = 0;
            foreach (char s in str)
            {
                strArr[str_idx++] = s.ToString();
            }
       
            string code = "";

          

            for (int i = 0; i < length; i++)
            {
                int idx = strArr.Length - (i + 1);
                code += strArr[idx];
            }
            return code;
        }
        /// <summary>
        /// 生成随机数（纯数字）数字之间有空格 用于语音验证
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string RndStrVoice(int length)
        {
            string str = "1,2,3,4,5,6,7,8,9,0";

            string[] strArr = str.Split(',');
            string code = string.Empty;

            Random random = new Random(DateTime.Now.Millisecond);

            for (int i = 0; i < length; i++)
            {
                code += strArr[random.Next(0, strArr.Length)] + " ";
            }
            return code;
        }

        /// <summary>
        /// 生成随机数（纯数字）数字之间有空格 用于语音验证
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        //public static string RndStrVoiceNew(int length)
        //{
        //    string str = "1,2,3,4,5,6,7,8,9,0";

        //    string[] strArr = str.Split(',');
        //    string code = string.Empty;

        //    Random random = new Random(DateTime.Now.Millisecond);

        //    for (int i = 0; i < length; i++)
        //    {
        //        code += strArr[random.Next(0, strArr.Length)] + "";
        //    }
        //    return code;
        //}
        #endregion

        #region 生成随机数（纯字母）
        /// <summary>
        /// 生成随机数（纯字母）
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string RndStrLetter(int length)
        {
            string str = "a,b,c,d,e,f,g,h,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z";

            string[] strArr = str.Split(',');
            string code = string.Empty;

            Random random = new Random(DateTime.Now.Millisecond);

            for (int i = 0; i < length; i++)
            {
                code += strArr[random.Next(0, strArr.Length)];
            }
            return code;
        }
        #endregion

        #region 随机数不重复概率的种子
        /// <summary>
        /// 随机数不重复概率的种子
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        private static int GetRandomSeed
        {
            get
            {
                byte[] bytes = new byte[4];

                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                rng.GetBytes(bytes);

                return BitConverter.ToInt32(bytes, 0);
            }
        }
        #endregion
        #endregion


        /// <summary>
        /// 判断某种特殊符号间隔的Id字符串是否包含某个Id。示例：
        /// 逗号间隔的字符串 "12,25,32" 是否包含 12 。
        /// 调用方式：bool existsId=StringUtils.StringContains("12,25,32","12");
        /// </summary>
        /// <param name="source"></param>
        /// <param name="item"></param>
        /// <param name="splitChar"></param>
        /// <returns></returns>
        public static bool StringContains(string source, string item, string splitChar = ",")
        {
            if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(item)) return false;
            return string.Format("{0}{1}{0}", splitChar, source).IndexOf(string.Format("{0}{1}{0}", splitChar, item)) > -1;
        }

        /// <summary>
        /// Sha1
        /// </summary>
        /// <param name="orgStr"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string Sha1Utils(string orgStr, string encode = "UTF-8")
        {
            var sha1 = new SHA1Managed();
            var sha1bytes = System.Text.Encoding.GetEncoding(encode).GetBytes(orgStr);
            byte[] resultHash = sha1.ComputeHash(sha1bytes);
            string sha1String = BitConverter.ToString(resultHash).ToLower();
            sha1String = sha1String.Replace("-", "");
            return sha1String;
        }
        public static string MD5Utils(string encypStr, string charset = "UTF-8")
        {
            string retStr;
            MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();

            //创建md5对象
            byte[] inputBye;
            byte[] outputBye;

            //使用GB2312编码方式把字符串转化为字节数组．
            try
            {
                inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr);
            }
            catch (Exception ex)
            {
                inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr);
            }
            outputBye = m5.ComputeHash(inputBye);

            retStr = System.BitConverter.ToString(outputBye);
            retStr = retStr.Replace("-", "").ToUpper();
            return retStr;
        }


        /// <summary>
        /// 生成随机数 
        /// </summary>
        /// <returns></returns>
        public static string GetPushUrlCode()
        {
            string YearDay = DateTime.Now.DayOfYear.ToString("000");
            Random r = new Random();
            string cr = r.Next(00000, 99999).ToString("00000");
            return DateTime.Now.Year.ToString().Substring(2, 2) + YearDay + cr;
        }

        /// <summary>
        /// 处理字符串为Null的问题
        /// </summary>
        /// <param name="val">原字符串</param>
        /// <returns></returns>
        public static string NullToEmpty(string val)
        {
            if (string.IsNullOrEmpty(val))
            {
                val = string.Empty;
            }
            return val;
        }

        /// <summary>
        /// 获得指定长度字符串
        /// </summary>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string GetRndStr(int len)
        {
            
            string _availableLetters = @"ABCDEFGHJKMNPRSTUVWXYZ2345678";
            List<char> code = new List<char>();
            Random rnd = new Random();
            string rndstr = string.Empty;
            for (int i = 0; i < len; i++)
            {
                int seed = rnd.Next(0, _availableLetters.Length - 1);
                char temp = _availableLetters[seed];
                rndstr += temp;
            }

            return rndstr;

        }



        /// <summary>
        /// Unicode编码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string EnUnicode(string str)
        {
            StringBuilder strResult = new StringBuilder();
            if (!string.IsNullOrEmpty(str))
            {
                for (int i = 0; i < str.Length; i++)
                {
                    strResult.Append("\\u");
                    strResult.Append(((int)str[i]).ToString("x"));
                }
            }
            return strResult.ToString();
        }

        /// <summary>
        /// Unicode解码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string DeUnicode(string str)
        {
            //最直接的方法Regex.Unescape(str);
            Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
            return reg.Replace(str, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
        }

        /// <summary>
        /// Base64编码
        /// </summary>
        /// <param name="code"></param>
        /// <param name="code_type"></param>
        /// <returns></returns>
        public static string EncodeBase64( string code,string code_type= "utf-8")
        {
            string encode = "";
            byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
            try
            {
                encode = Convert.ToBase64String(bytes);
            }
            catch
            {
                encode = code;
            }
            return encode;
        }
        /// <summary>
        /// Base64解码
        /// </summary>
        /// <param name="code"></param>
        /// <param name="code_type"></param>
        /// <returns></returns>
        public static string DecodeBase64(string code, string code_type = "utf-8")
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(code);
            try
            {
                decode = Encoding.GetEncoding(code_type).GetString(bytes);
            }
            catch
            {
                decode = code;
            }
            return decode;
        }


    }

}
